/*
 * Project: BoboDesignPattern
 * 
 * File Created at 2019年8月3日
 * 
 * Copyright 2012 Greenline.com Corporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Greenline Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Greenline.com.
 */
package test.net;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * @Type ServerSockeNio
 * @Desc
 * @author 52489
 * @date 2019年8月3日
 * @Version V1.0
 */
public class ServerSockeNio {

    static byte[] bytes = new byte[1024];
    static List<SocketChannel> list = new ArrayList<>();
    static ByteBuffer byteBuffer = ByteBuffer.allocate(512);

    public static void main(String[] args) {
        ServerSocketChannel serverSocketChannel;
        try {
            serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.bind(new InetSocketAddress(8888));
            serverSocketChannel.configureBlocking(false);
            while (true) {
                SocketChannel socketChannel = serverSocketChannel.accept();
                if (socketChannel == null) {
                    Thread.sleep(1000);
                    System.out.println("no coon");
                    for (SocketChannel client : list) {
                        int k = client.read(byteBuffer);
                        if (k > 0) {
                            byteBuffer.flip();
                            System.out.println(byteBuffer.toString());

                        }
                    }
                } else {
                    System.out.println("-----------------------conn--------------------");
                    socketChannel.configureBlocking(false);
                    list.add(socketChannel);
                    for (SocketChannel client : list) {
                        int i = client.read(byteBuffer);
                        if (i > 0) {
                            byteBuffer.flip();
                            System.out.println(byteBuffer.toString());
                        }
                    }
                }
            }

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}
